package cn.iocoder.yudao.module.wine.controller.admin.businessuser;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserRespVO;
import cn.iocoder.yudao.module.member.convert.user.MemberUserConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordOpeVO;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordPageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordRespVO;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user.BrokerageUserPageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user.BrokerageUserRespVO;
import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageRecordConvert;
import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageUserConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageRecordDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageRecordService;
import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageUserService;
import cn.iocoder.yudao.module.wine.api.BusinessUserApi;
import cn.iocoder.yudao.module.wine.api.dto.BusinessUserDTO;
import cn.iocoder.yudao.module.wine.controller.admin.businessuser.vo.*;
import cn.iocoder.yudao.module.wine.service.businessuser.BusinessUserService;

import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.annotation.security.PermitAll;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

@Tag(name = "管理后台 - 商家")
@RestController
@RequestMapping("/wine/business-user")
@Validated
public class BusinessUserController {

    @Resource
    private BusinessUserService businessUserService;

    @Resource
    private BrokerageUserService brokerageUserService;

    @Resource
    private BrokerageRecordService brokerageRecordService;

    @Resource
    private BusinessUserApi businessUserApi;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private MemberUserService memberUserService;
    /**
     * 后台手动创建商家
     * @param createReqVO
     * @return
     */
    @PostMapping("/create")
    @Operation(summary = "创建商家")
    @PreAuthorize("@ss.hasPermission('wine:business-user:create')")
    public CommonResult<Long> createBusinessUser(@Valid @RequestBody BusinessUserSaveReqVO createReqVO) {
        return success(businessUserService.createBusinessUser(createReqVO));
    }

    /**
     * 后台创建个人团长
     * @param createReqVO
     * @return
     */
    @PostMapping("/create-team")
    @PermitAll
    @Operation(summary = "创建团长")
    public CommonResult<Integer> createTeam(@Valid @RequestBody TeamUserSaveReqVO createReqVO) {
        return success(businessUserService.createTeamUser(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新商家")
    @PreAuthorize("@ss.hasPermission('wine:business-user:update')")
    public CommonResult<Boolean> updateBusinessUser(@Valid @RequestBody BusinessUserSaveReqVO updateReqVO) {
        businessUserService.updateBusinessUser(updateReqVO);
        return success(true);
    }

    @PutMapping("/audit")
    @Operation(summary = "审核商家")
    @PreAuthorize("@ss.hasPermission('wine:business-user:update')")
    public CommonResult<Boolean> auditBusinessUser(@Valid @RequestBody BusinessUserSaveReqVO updateReqVO) {
        businessUserService.auditBusinessUser(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除商家")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('wine:business-user:delete')")
    public CommonResult<Boolean> deleteBusinessUser(@RequestParam("id") Long id) {
        businessUserService.deleteBusinessUser(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得商家")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('wine:business-user:query')")
    public CommonResult<BusinessUserRespVO> getBusinessUser(@RequestParam("id") Long id) {
        BusinessUserRespVO businessUserRespVO = businessUserService.getBusinessUser(id);
        businessUserRespVO.setAreaName(AreaUtils.format(businessUserRespVO.getAreaId(), " "));
        return success(businessUserRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得商家分页")
    @PreAuthorize("@ss.hasPermission('wine:business-user:query')")
    public CommonResult<PageResult<BusinessUserRespVO>> getBusinessUserPage(@Valid BusinessUserPageReqVO pageReqVO) {
        PageResult<BusinessUserRespVO> pageResult = businessUserService.getBusinessUserPage(pageReqVO);
        List<BusinessUserRespVO> list = pageResult.getList();
        //所有商家用户ID
        Set<Long> userIds = convertSet(pageResult.getList(), BusinessUserRespVO::getUserId);
        if(!userIds.isEmpty()){
            List<BrokerageUserDO> brokerageUserlist = brokerageUserService.getBrokerageUserList(userIds);
            //所有上级商家用户ID
            Set<Long> bindUserIds = convertSet(brokerageUserlist, BrokerageUserDO::getBindUserId);
            Map<Long, MemberUserRespDTO> bindUserMap = memberUserApi.getUserMap(bindUserIds);

            Map<Long, BrokerageUserDO> brokerageUserMap = convertMap(brokerageUserlist, BrokerageUserDO::getId);

            for (BusinessUserRespVO userVO : list) {
                // 上级用户ID绑定
                BrokerageUserDO source = brokerageUserMap.get(userVO.getUserId());
                Optional.ofNullable(source).ifPresent(user -> userVO.setBindUserId(user.getBindUserId()));
            }
            for (BusinessUserRespVO userVO : list) {
                // 上级用户信息绑定
                MemberUserRespDTO source = bindUserMap.get(userVO.getBindUserId());
                Optional.ofNullable(source).ifPresent(user -> userVO.setBindUserName(user.getName()));
            }
        }

        List<BusinessUserRespVO> collect = list.stream().peek(item -> {
            item.setAreaName(AreaUtils.format(item.getAreaId()," "));
        }).collect(Collectors.toList());
        pageResult.setList(collect);
        return success(pageResult);
    }


    @GetMapping("/export-excel")
    @Operation(summary = "导出商家 Excel")
    @PreAuthorize("@ss.hasPermission('wine:business-user:export')")
    @OperateLog(type = EXPORT)
    public void exportBusinessUserExcel(@Valid BusinessUserPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<BusinessUserRespVO> list = businessUserService.getBusinessUserPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "商家配置.xls", "数据", BusinessUserRespVO.class,
                        BeanUtils.toBean(list, BusinessUserRespVO.class));
    }

    @GetMapping("/info")
    @Operation(summary = "获得商家")
    @Parameter(name = "userId", description = "用户编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('wine:business-user:query')")
    public CommonResult<BusinessUserRespVO> getBusinessUserInfo(@RequestParam("userId") Long userId) {
        BusinessUserRespVO businessUserRespVO = businessUserService.getBusinessUserInfo(userId);
        Integer allAmount = brokerageRecordService.getBusinessUserRecordNum(userId);
        businessUserRespVO.setAllAmount(allAmount);
        businessUserRespVO.setAreaName(AreaUtils.format(businessUserRespVO.getAreaId(), " "));

        return success(businessUserRespVO);
    }

    @PostMapping("/approve")
    @Operation(summary = "后台按条提现操作")
    @PreAuthorize("@ss.hasPermission('wine:business-user:create')")
    public CommonResult<Boolean> approveBrokerageRecord(@Valid @RequestBody BrokerageRecordOpeVO opeVO) {
        brokerageRecordService.approveBrokerageRecordIn(opeVO.getUserId(), opeVO.getIds(), opeVO.getRemark());
        return success(true);
    }

    //只是团长
    @GetMapping("/team-page")
    @Operation(summary = "获得团长用户分页")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<PageResult<MemberUserRespVO>> getTeamUserPage(@Valid MemberUserPageReqVO pageVO) {
        PageResult<MemberUserDO> pageResult = memberUserService.getTeamUserPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }
        Set<Long> userIds = convertSet(pageResult.getList(), MemberUserDO::getId);

        PageResult<MemberUserRespVO> pageList = MemberUserConvert.INSTANCE.convertPage(pageResult);

        if(!userIds.isEmpty()) {
            List<BrokerageUserDO> brokerageUserlist = brokerageUserService.getBrokerageUserList(userIds);

            Map<Long, BrokerageUserDO> brokerageUserMap = convertMap(brokerageUserlist, BrokerageUserDO::getId);

            for (MemberUserRespVO userVO : pageList.getList()) {
                // 商家用户信息
                BrokerageUserDO source = brokerageUserMap.get(userVO.getId());
                Optional.ofNullable(source).ifPresent(user -> userVO.setBrokerageEnabled(user.getBrokerageEnabled()));
            }
        }

        return success(pageList);

    }
    //只是商家
    @GetMapping("/business-page")
    @Operation(summary = "获得商家用户分页")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<PageResult<MemberUserRespVO>> getBusinessUserPage(@Valid MemberUserPageReqVO pageVO) {
        PageResult<MemberUserDO> pageResult = memberUserService.getBusinessUserPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }
        //所有商家用户ID
        Set<Long> userIds = convertSet(pageResult.getList(), MemberUserDO::getId);

        PageResult<MemberUserRespVO> pageList = MemberUserConvert.INSTANCE.convertPage(pageResult);

        if(!userIds.isEmpty()) {
            List<BrokerageUserDO> brokerageUserlist = brokerageUserService.getBrokerageUserList(userIds);
            //所有上级商家用户ID
            Set<Long> bindUserIds = convertSet(brokerageUserlist, BrokerageUserDO::getBindUserId);
            Map<Long, MemberUserRespDTO> bindUserMap = memberUserApi.getUserMap(bindUserIds);

            Map<Long, BrokerageUserDO> brokerageUserMap = convertMap(brokerageUserlist, BrokerageUserDO::getId);

            for (MemberUserRespVO userVO : pageList.getList()) {
                // 上级用户ID绑定
                BrokerageUserDO source = brokerageUserMap.get(userVO.getId());
                Optional.ofNullable(source).ifPresent(user -> userVO.setBindUserId(user.getBindUserId()));
            }
            for (MemberUserRespVO userVO : pageList.getList()) {
                // 上级用户信息绑定
                MemberUserRespDTO source = bindUserMap.get(userVO.getBindUserId());
                Optional.ofNullable(source).ifPresent(user -> userVO.setBindUserName(user.getName()));
            }
        }
        return success(pageList);
    }

    @GetMapping("/user-page")
    @Operation(summary = "获得分销商家用户分页")
    @PreAuthorize("@ss.hasPermission('wine:brokerage-user:query')")
    public CommonResult<PageResult<BrokerageUserRespVO>> getBrokerageUserPage(@Valid BrokerageUserPageReqVO pageVO) {
        // 分页查询
        PageResult<BrokerageUserDO> pageResult = brokerageUserService.getBrokerageUserPage(pageVO);
        // 查询用户信息
        Set<Long> userIds = convertSet(pageResult.getList(), BrokerageUserDO::getId);
        Map<Long, MemberUserRespDTO> userMap = memberUserApi.getUserMap(userIds);
        Map<Long, BusinessUserDTO> businessUserMap = businessUserApi.getBusinessUserMap(userIds);
        // 拼接返回
        PageResult<BrokerageUserRespVO> result = BrokerageUserConvert.INSTANCE.convertPage(pageResult, userMap);
        for (BrokerageUserRespVO userVO : result.getList()) {
            // 商家用户信息
            BusinessUserDTO source = businessUserMap.get(userVO.getId());
            Optional.ofNullable(source).ifPresent(user ->
                    userVO
                            .setOpenTime(user.getOpenTime())
                            .setOverTime(user.getOverTime())
                            .setCompanyName(user.getCompanyName()));


        }
        return success(result);
    }
    //与佣金记录控制器的一样，扩展关联表使用
    @GetMapping("/record-page")
    @Operation(summary = "获得佣金记录分页")
    @PreAuthorize("@ss.hasPermission('wine:brokerage-user:query')")
    public CommonResult<PageResult<BrokerageRecordRespVO>> getBrokerageRecordPage(@Valid BrokerageRecordPageReqVO pageVO) {
        PageResult<BrokerageRecordDO> pageResult = brokerageRecordService.getBrokerageRecordPage(pageVO);

        // 查询用户信息
        Set<Long> userIds = convertSet(pageResult.getList(), BrokerageRecordDO::getUserId);
        userIds.addAll(convertList(pageResult.getList(), BrokerageRecordDO::getSourceUserId));
        Map<Long, MemberUserRespDTO> userMap = memberUserApi.getUserMap(userIds);
        // 拼接数据
        return success(BrokerageRecordConvert.INSTANCE.convertPage(pageResult, userMap));
    }
}
